# coding: utf-8
from collections import deque
from typing import Callable

from PySide6.QtCore import QThread, Signal

from .base import RequestHandler, EventSignalBus, QueueThread


class WorkerThread(QThread):
    result = Signal(object, object)  # 返回结果信息信号
    failed = Signal(object)  # 返回失败信息信号
    messageSignal = Signal(object)  # 返回提示信息信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.tasks = deque()

    def addTask(self, func, *args, slot: Callable = None, **kwargs):
        self.tasks.append((func, args, kwargs, slot))
        if not self.isRunning():
            self.start()

    def run(self):
        while self.tasks:
            func, args, kwargs, slot = self.tasks.popleft()
            try:
                result = func(*args, **kwargs)
                self.result.emit(slot, result)
            except Exception as e:
                self.failed.emit(str(e))


workerSignalBus = EventSignalBus()


def workerRequest(func: Callable, *args, slot=None, **kwargs):
    request = RequestHandler(func, slot, *args, **kwargs)
    workerSignalBus.fetchDataSignal.emit(request)


class WorkerQueueThread(QueueThread):
    def __init__(self, parent=None):
        super().__init__(parent)
        workerSignalBus.fetchDataSignal.connect(self.addTask)
        self.result.connect(workerSignalBus.resultSignal)
